import formModel from './components/formModel.vue'// 列表
import editOrAdd from './components/editAndAdd.vue'// 新增编辑
export default {
  components: {
    formModel,
    editOrAdd
  },
  filters: {
    cutString(str, len) {
      if (str.length * 2 <= len) {
        return str
      }
      let strlen = 0
      let s = ''
      for (let i = 0; i < str.length; i++) {
        s = s + str.charAt(i)
        if (str.charCodeAt(i) > 128) {
          strlen = strlen + 2
          if (strlen >= len) {
            return s.substring(0, s.length - 1) + '...'
          }
        } else {
          strlen = strlen + 1
          if (strlen >= len) {
            return s.substring(0, s.length - 2) + '...'
          }
        }
      }
      return s
    },

    cardType(num) {
      let text = ''
      switch (Number(num)) {
        case 4:
          text = '充值系列'
          break
        case 1:
          text = '月卡系列'
          break
        case 2:
          text = '次卡系列'
          break
        case 3:
          text = '计时系列'
          break
        default:
          text = ''
          break
      }
      return text
    },
    tableCardType(num) {
      let text = ''
      switch (Number(num)) {
        case 4:
          text = '充值卡'
          break
        case 1:
          text = '月卡'
          break
        case 2:
          text = '次卡'
          break
        case 3:
          text = '计时卡'
          break
        default:
          text = ''
          break
      }
      return text
    }
  },
  data() {
    const validateMoney = (rule, value, callback) => {
      if (!value) {
        callback(new Error('价格不能为空'))
      } else if (value.indexOf('.') !== -1 && value.split('.').length > 2) {
        callback(new Error('请输入正确的数值')) // 防止输入多个小数点
      } else if (value.indexOf('.') !== -1 && value.split('.')[1].length > 2) {
        callback(new Error('请输入正确的小数位数')) // 小数点后两位
      } else if (value.charAt(0) === '.') {
        callback(new Error('请输入正确的数值')) // 防止输入多个小数点
        console.log(value.charAt(0))
      } else {
        callback()
      }
    }
    const initialPrice = (rule, value, callback) => {
      if (Number(value) < 6) {
        callback(new Error('起步价不能低于6元'))
      } else {
        callback()
      }
    }
    return {
      id: '', // 编辑选择id
      index: 0, // 编辑当前下标
      validity: '优惠有效期',
      sellingTitle: '销售价',
      isHandleEdit: false,
      addOrEdit: '添加',
      title: '新增会员卡',
      cardListEdit: {
        4: [],
        1: [],
        2: [],
        3: []
      },
      total: 0,
      pageSize: 10,
      pageIndex: 1,
      isAddModel: false, // 新增系列模态框
      preservation: false, // 保存
      dialogVisible: false,
      disabled: false,
      formLabelWidth: '120px', // label宽度
      dialogFormVisible: false, // 模态框
      carList: [],
      value: true,
      formInline: {
        selectValue: null,
        searchKey: '' // 会员卡搜索值
      },
      // 分类
      tag: [
        {
          id: 4,
          text: '充值',
          type: 'info'
        },
        {
          id: 1,
          text: '月卡',
          type: 'info'
        },
        {
          id: 2,
          text: '次卡',
          type: 'info'
        },
        {
          id: 3,
          text: '计时',
          type: 'info'
        }
      ],
      arr: [], // 会员卡类型
      rulesName: {
        name: [
          {
            required: true,
            message: '请输入会员卡包名',
            trigger: 'blur'
          }
        ],
        arr: [
          {
            type: 'array',
            required: true,
            message: '请输入会员卡包名',
            trigger: 'blur'
          }
        ]
      },
      // 表单
      form: {
        pageId: '',
        stop: 0,
        id: null,
        cardType: '',
        name: '', // 会员卡包名
        xlNmae: '', // 系列名字
        contain: '', // 卡内包含
        sellingPrice: 0, // 销售价
        originalPrice: 0, // 原价
        initial: 0, // 初始扣除价格
        buySet: 0, // 购买设置
        limit: 0, // 消费限制
        unitPrice: 0, // 核销单价
        term: 0,
        deadline: '',
        day: null, // 剩余多少天
        /* minute: '', // 实际分钟数
          containfrequency: '', // 包含次数
          actualfrequency: '', // 实际次数
          containTime: '', // 包含时间
          actualMinute: '', // 实际分钟数 */
        img: '' // 套餐图

      },
      // 规则
      rules: {
        initial: [
          {
            required: true,
            message: '请输入价格',
            trigger: 'blur'
          },
          {
            type: 'string',
            required: true,
            trigger: 'blur',
            validator: validateMoney
          },
          {
            type: 'string',
            required: true,
            trigger: 'blur',
            validator: initialPrice
          }
        ],
        // 卡包名
        /* name: [
          {
            required: true,
            message: '请输入活动名称',
            trigger: 'blur'
          },
          {
            min: 3,
            max: 5,
            message: '长度在 3 到 5 个字符',
            trigger: 'blur'
          }
        ], */
        // 系列名称
        xlNmae: [
          {
            required: true,
            message: '请输入系列名称',
            trigger: 'blur'
          }
        ],
        // 卡包包含
        contain: [
          {
            required: true,
            message: '请输入价格',
            trigger: 'blur'
          },
          { type: 'number', message: '有效期为数字值', trigger: 'blur' }
        ],
        // 销售价
        sellingPrice: [
          {
            required: true,
            message: '请输入价格',
            trigger: 'blur'
          },
          {
            type: 'string',
            required: true,
            trigger: 'blur',
            validator: validateMoney
          }
        ],
        // 原价
        originalPrice: [
          {
            required: true,
            message: '请输入原价',
            trigger: 'blur'
          },
          {
            type: 'string',
            required: true,
            trigger: 'blur',
            validator: validateMoney
          }
        ],
        /* buySet: [
          {
            required: true,
            message: '请输入购买设置',
            trigger: 'blur'
          },
          { type: 'number', message: '有效期为数字值' }
        ], */
        // 消费限制
        limit: [
          {
            required: true,
            message: '请输入消费限制',
            trigger: 'blur'
          },
          {
            type: 'string',
            required: true,
            trigger: 'blur',
            validator: validateMoney
          }
        ],

        /* limitNull: [
          {
            required: false
          }
        ], */

        // 有效期
        term: [
          {
            required: true,
            message: '请输入有效期',
            trigger: 'blur'
          },
          { type: 'number', message: '有效期为数字值', trigger: 'blur' }
        ],
        // 没有有效期
        /* termNull: [
          {
            required: false
          }
        ], */
        // 核销单价
        unitPrice: [
          {
            required: true,
            message: '请输入价格',
            trigger: 'blur'
          },
          {
            type: 'string',
            required: true,
            trigger: 'blur',
            validator: validateMoney
          }
        ],

        img: [
          {
            required: true,
            message: '请上传图片',
            trigger: 'blur'
          }
        ],
        deadline: [
          {
            required: true,
            message: '请上传截至时间',
            trigger: 'blur'
          }
        ]
      },

      editList: {}, // 编辑信息
      type: 0,
      status: 0
    }
  },
  created() {
    this.getCardList()
  },
  // 4充值1包月2次卡3分钟
  methods: {
    changeContain(e) {
      if (this.editList.id) {
        this.cardListEdit[this.type][this.index].free_Cost = e
      }
    },
    changeName(e) {
      console.log(this.type, this.index)
      if (this.editList.id) {
        this.cardListEdit[this.type][this.index].coupon_Name = e
      }
    },
    // 置空
    clearValue(type) {
      this.form = {
        cardType: type,
        pageId: '',
        stop: '',
        name: this.form.name,
        xlNmae: '',
        contain: '',
        sellingPrice: '',
        originalPrice: '',
        buySet: '',
        limit: '',
        unitPrice: '', // 核销单价
        /* minute: '', // 实际分钟数
        containfrequency: '', // 包含次数
        actualfrequency: '', // 实际次数
        containTime: '', // 包含时间 */
        img: '',
        term: '',
        initial: '',
        deadline: '', // 截至
        id: ''
      }
    },
    newClearValue(type) {
      this.form = {
        pageId: this.form.pageId,
        cardType: type,
        stop: '',
        name: this.form.name,
        xlNmae: '',
        contain: '',
        sellingPrice: '',
        originalPrice: '',
        buySet: '',
        limit: '',
        unitPrice: '', // 核销单价
        img: '',
        term: '',
        initial: '',
        deadline: '', // 截至
        id: ''
      }
    },
    // 图片上传成功
    success(e) {
      console.log(e)
      this.form.img = e
    },
    onDate(date) {
      const end = new Date(date).getTime()
      const start = new Date().getTime()
      const time = end - start
      const day = Math.floor(time / 86400000) < 0 ? 0 : Math.floor(time / 86400000)
      if (this.deadline === '0001-01-01T00:00:00') return false
      if (day === 0) {
        this.$set(this.form, 'day', day)
      } else {
        this.$set(this.form, 'day', day + 1)
      }
    },

    // 保存
    async SaveSelfServiceCarWashCard() {
      try {
        const res = await this.$api.menberCard.SaveSelfServiceCarWashCard(this.editList)
        if (res.code === 200) {
          if (this.form.id) {
            if (this.type === 4) {
              this.cardListEdit[4].splice(this.index, 1, this.editList)
            } else if (this.type === 1) {
              this.cardListEdit[1].splice(this.index, 1, this.editList)
            } else if (this.type === 2) {
              this.cardListEdit[2].splice(this.index, 1, this.editList)
            } else if (this.type === 3) {
              this.cardListEdit[3].splice(this.index, 1, this.editList)
            }
            this.$message({
              message: '保存成功',
              type: 'success'
            })
          } else {
            this.editList.id = res.data
            if (this.type === 4) {
              this.cardListEdit[4].push(this.editList)
            } else if (this.type === 1) {
              this.cardListEdit[1].push(this.editList)
            } else if (this.type === 2) {
              this.cardListEdit[2].push(this.editList)
            } else if (this.type === 3) {
              this.cardListEdit[3].push(this.editList)
            }
            this.$message({
              message: '新增成功',
              type: 'success'
            })
          }
        }
        this.isAddModel = false
        this.getCardList()
        // this.getCardEdit()
      } catch (e) {
        // TODO handle the exception
      }
    },
    // 会员卡模板详情
    async getByDetile(id, type) {
      try {
        const data = {
          'id': id
        }
        const res = await this.$api.menberCard.GetSelfServiceCarWashCardByDetile(data)
        this.editList = res.data
        const end = new Date(this.editList.deadline).getTime()
        const strat = new Date().getTime()
        const time = end - strat
        const day = Math.floor(time / 86400000)// 相差天数
        let price
        let useAging
        // 卡内包含1没有
        if (this.editList.card_Type === 2) {
          price = this.editList.limit_Times
        } else if (this.editList.card_Type === 3) {
          price = this.editList.total_Time
        } else if (this.editList.card_Type === 4) {
          price = this.editList.card_Cost
        } else {
          price = null
        }
        // 有效期4没有
        if (this.editList.card_Type !== 4) {
          useAging = this.editList.use_Aging
        } else if (this.editList.card_Type === 4) {
          useAging = 0
        }
        this.form = {
          id: this.editList.id,
          stop: this.editList.timesPauseMinutes,
          name: this.form.name,
          pageId: this.form.pageId,
          xlNmae: this.editList.coupon_Name || '', // 系列名字
          contain: price, // 卡内包含
          sellingPrice: this.editList.sale_Price + '' || '', // 销售价
          originalPrice: this.editList.normal_Price + '' || '', // 原价
          buySet: this.editList.free_Cost + '' || '', // 购买设置
          limit: this.editList.times_Seconds + '' || '', // 消费限制
          // minute: null, // 实际分钟数
          unitPrice: this.editList.settlement + '' || '', // 核销单价
          /*  containfrequency: null, // 包含次数
          actualfrequency: null, // 实际次数
          containTime: null, // 包含时间
          actualMinute: null, // 实际分钟数 */
          img: this.editList.pic_URL || '', // 套餐图
          term: useAging, // 有效期
          initial: this.editList.initial_Deduction_Cost + '' || '',
          deadline: this.editList.deadline || '0001-01-01T00:00:00', // 截至
          cardType: type,
          day: day
        }
      } catch (e) {
        // TODO handle the exception
      }
    },

    // 处理时间格式
    /* dateFormat(value) {
      let time = ''
      time = value.addTime.replace(/\T/g, ' ')
      return time
    }, */
    // 表格删除
    async deleteCard(index, row) {
      try {
        const data = {
          'id': row.id
        }
        const res = await this.$api.menberCard.DeleteSelfServiceCarWashCardPackageById(data)
        console.log(res)
        if (res.code === 200) {
          this.$message({
            message: res.data,
            type: 'success'
          })
          this.getCardList()
        } else {
          this.$message({
            message: res.data,
            type: 'warning'
          })
        }
      } catch (e) {
        // TODO handle the exception
      }
    },
    // 新增编辑删除
    async del(row, index, type) {
      try {
        const data = {
          'id': row
        }
        const res = await this.$api.menberCard.DeleteSelfServiceCarWashCard(data)
        console.log(res)
        if (res.code === 200) {
          this.$message({
            message: res.data,
            type: 'success'
          })
          if (type === 4) {
            this.cardListEdit[4].splice(index, 1)
          } else if (type === 1) {
            this.cardListEdit[1].splice(index, 1)
          } else if (type === 2) {
            this.cardListEdit[2].splice(index, 1)
          } else if (type === 3) {
            this.cardListEdit[3].splice(index, 1)
          }
          // this.getCardEdit()
        } else {
          this.$message({
            message: res.data,
            type: 'success'
          })
        }
      } catch (e) {
        // TODO handle the exception
      }
    },
    // 处理上架状态
    async newUpDataStatus(e) {
      try {
        const data = {
          'id': e.id,
          'status': e.status
        }
        const res = await this.$api.menberCard.SetSelfServiceCarWashCardPackageStatusById(data)
        console.log(res)
        this.getCardList()
      } catch (e) {
        // TODO handle the exception
      }
    },
    async upDataStatus(e) {
      try {
        const data = {
          'id': e.id,
          'status': e.status
        }
        const res = await this.$api.menberCard.UpdateSelfServiceCarWashCardStatus(data)
        console.log(res)
        this.getCardList()
      } catch (e) {
        // TODO handle the exception
      }
    },
    async GetSelfServiceCarWashCardPackageById(id) {
      try {
        const data = {
          'id': id
        }
        const res = await this.$api.menberCard.GetSelfServiceCarWashCardPackageById(data)
        console.log(res)
        this.form.name = res.data.package_Name
        this.form.pageId = res.data.id
      } catch (e) {
        // TODO handle the exception
      }
    },
    // 获取会员卡包列表
    async getCardList() {
      try {
        const data = {
          'pageIndex': this.pageIndex,
          'pageSize': this.pageSize,
          'package_Name': this.searchKey
        }
        const res = await this.$api.menberCard.GetSelfServiceCarWashCardPackageByName(data)
        // console.log(res, '会员卡包')
        this.carList = res.data.list
        this.total = res.data.total
      } catch (e) {
        // TODO handle the exception
      }
    },
    async getCardTypeList(id) {
      const data = {
        'self_Service_Car_Wash_Card_Package_Id': id,
        'washType': 0
      }
      const res = await this.$api.menberCard.GetSelfServiceCarWashCardListByPackageId(data)
      const list = res.data
      list.map(v => {
        if (v.card_Type === 4) {
          this.cardListEdit[4].push(v)
        } else if (v.card_Type === 1) {
          this.cardListEdit[1].push(v)
        } else if (v.card_Type === 2) {
          this.cardListEdit[2].push(v)
        } else if (v.card_Type === 3) {
          this.cardListEdit[3].push(v)
        }
      })
      console.log(list, '会员卡')
    },
    // 添加or添加
    save() {
      console.log(this.form.pageId, 'id')
      // editList编辑列表
      if (!this.form.id) {
        delete this.form.id
      }
      if (!this.form.pageId) {
        delete this.form.pageId
      }
      const that = this
      if (this.form.cardType === 4) { // 编辑充值的会员卡card_Cost
        that.editList = {
          id: this.form.id,
          self_Service_Car_Wash_Card_Package_Id: this.form.pageId,
          package_Name: this.form.name,
          timesPauseMinutes: Number(this.form.stop),
          coupon_Name: this.form.xlNmae, // 系列名字
          sale_Price: Number(this.form.sellingPrice) || 0, // 销售价
          normal_Price: Number(this.form.originalPrice) || 0, // 原价
          free_Cost: Number(this.form.buySet) || 0, // 购买设置
          // times_Seconds: Number(this.form.limit) || 0, // 消费限制
          settlement: Number(this.form.unitPrice) || 0, // 核销单价
          pic_URL: this.form.img, // 套餐图
          use_Aging: 0, // 有效期
          initial_Deduction_Cost: Number(this.form.initial) || 6, // 初始扣除
          // deadline: this.form.deadline || '',
          card_Type: this.form.cardType, // 会员卡类型
          card_Cost: Number(this.form.contain) || 0
        }
      } else if (this.form.cardType === 2) { // limit_Times次卡价值
        that.editList = {
          id: this.form.id,
          self_Service_Car_Wash_Card_Package_Id: this.form.pageId,
          package_Name: this.form.name,
          timesPauseMinutes: Number(this.form.stop),
          coupon_Name: this.form.xlNmae, // 系列名字
          limit_Times: Number(this.form.contain) || 0, // 卡内包含
          sale_Price: Number(this.form.sellingPrice) || 0, // 销售价
          normal_Price: Number(this.form.originalPrice) || 0, // 原价
          free_Cost: Number(this.form.buySet) || 0, // 购买设置
          times_Seconds: Number(this.form.limit) || 0, // 消费限制
          settlement: Number(this.form.unitPrice) || 0, // 核销单价
          pic_URL: this.form.img, // 套餐图
          use_Aging: Number(this.form.term) || 0, // 有效期
          // initial_Deduction_Cost: Number(this.form.initial) || 1, // 初始扣除
          deadline: this.form.deadline || '0001-01-01T00:00:00',
          card_Type: this.form.cardType // 会员卡类型
        }
      } else if (this.form.cardType === 1) { // 月卡use_Aging
        that.editList = {
          id: this.form.id,
          self_Service_Car_Wash_Card_Package_Id: this.form.pageId,
          package_Name: this.form.name,
          timesPauseMinutes: Number(this.form.stop),
          coupon_Name: this.form.xlNmae, // 系列名字
          use_Aging: Number(this.form.term) || 0, // 卡内包含
          sale_Price: Number(this.form.sellingPrice) || 0, // 销售价
          normal_Price: Number(this.form.originalPrice) || 0, // 原价
          free_Cost: Number(this.form.buySet) || 0, // 购买设置
          times_Seconds: Number(this.form.limit) || 0, // 消费限制
          settlement: Number(this.form.unitPrice) || 0, // 核销单价
          pic_URL: this.form.img, // 套餐图
          // use_Aging: Number(this.form.term) || 0, // 有效期
          // initial_Deduction_Cost: Number(this.form.initial) || 1, // 初始扣除
          deadline: this.form.deadline || '0001-01-01T00:00:00',
          card_Type: this.form.cardType // 会员卡类型
        }
      } else if (this.form.cardType === 3) { // total_Time计时总时间
        that.editList = {
          id: this.form.id,
          self_Service_Car_Wash_Card_Package_Id: this.form.pageId,
          package_Name: this.form.name,
          timesPauseMinutes: Number(this.form.stop),
          coupon_Name: this.form.xlNmae, // 系列名字
          total_Time: Number(this.form.contain), // 卡内包含
          sale_Price: Number(this.form.sellingPrice) || 0, // 销售价
          normal_Price: Number(this.form.originalPrice) || 0, // 原价
          free_Cost: Number(this.form.buySet) || 0, // 购买设置
          // times_Seconds: Number(this.form.limit) || 0, // 消费限制
          settlement: Number(this.form.unitPrice) || 0, // 核销单价
          pic_URL: this.form.img, // 套餐图
          use_Aging: Number(this.form.term) || 0, // 有效期
          // initial_Deduction_Cost: Number(this.form.initial) || 1, // 初始扣除
          deadline: this.form.deadline || '0001-01-01T00:00:00',
          card_Type: this.form.cardType // 会员卡类型
        }
      }
      this.SaveSelfServiceCarWashCard()
    },

    // tag切换
    changeTag(id) {
      if (this.arr.includes(id)) {
        this.arr = this.arr.filter(ele => {
          return ele !== id
        })
      } else {
        this.arr.push(id)
      }
      if (!this.arr.length) {
        this.bodyClose()
      }
    },

    // 二级弹窗关闭
    bodyClose() {
      if (this.editList.id) {
        this.cardListEdit[this.type][this.index].free_Cost = this.editList.free_Cost
        this.cardListEdit[this.type][this.index].coupon_Name = this.editList.coupon_Name
      }
      this.id = ''
      this.isAddModel = false
    },
    async SaveSelfServiceCarWashCardPackage() {
      try {
        const data = {
          'id': this.form.pageId,
          'package_Name': this.form.name
        }
        const res = await this.$api.menberCard.SaveSelfServiceCarWashCardPackage(data)
        console.log(res)
        this.getCardList()
      } catch (e) {
        // TODO handle the exception
      }
    },
    // 列表编辑获取type列表
    handleEdit(index, row) {
      /* this.cardListEdit = {
        4: [],
        1: [],
        2: [],
        3: []
      } */
      this.arr = [4, 1, 2, 3]
      this.dialogFormVisible = true
      this.GetSelfServiceCarWashCardPackageById(row.id)
      this.getCardTypeList(row.id)
      // this.edit(row, 1, row.card_Type)
    },

    // 分别获取type列表（一级模态框）
    async getCardEdit() {
      try {
        const data = {
          'pageIndex': 1,
          'pageSize': 100,
          'coupon_Name': '',
          'card_Type': null
        }
        const res = await this.$api.menberCard.GetSelfServiceCarWashCardList(data)
        // console.log(res.data.list, '详情列表')
        const list = res.data.list
        list.map(v => {
          if (v.card_Type === 4) {
            this.cardListEdit[4].push(v)
          } else if (v.card_Type === 1) {
            this.cardListEdit[1].push(v)
          } else if (v.card_Type === 2) {
            this.cardListEdit[2].push(v)
          } else if (v.card_Type === 3) {
            this.cardListEdit[3].push(v)
          }
        })
      } catch (e) {
        // TODO handle the exception
      }
    },
    // 系列列表编辑(编辑)（一级模态框）
    edit(item, type, cardType, index) {
      this.index = index
      this.id = item.id
      this.type = cardType
      this.newClearValue(cardType)
      this.title = '编辑会员卡'
      this.addOrEdit = '保存'
      if (cardType === 1) {
        this.validity = '卡内包含'
      } else {
        this.validity = '优惠有效期'
      }

      this.isAddModel = true
      this.getByDetile(item.id, cardType)
    },
    // 默认图点击新增（一级模态框）
    add(type) {
      this.type = type
      this.title = '新增会员卡'
      this.addOrEdit = '添加'
      this.isAddModel = true
      this.editList = {}
      if (type === 1) {
        this.validity = '卡内包含'
      } else {
        this.validity = '优惠有效期'
      }
      if (type === 4) {
        this.sellingTitle = '销售价'
      } else {
        this.sellingTitle = '标价'
      }
      this.newClearValue(type)
    },
    // 新增确定（一级模态框）
    determine() {
      this.dialogFormVisible = false
      this.SaveSelfServiceCarWashCardPackage()
      this.cardListEdit = {
        4: [],
        1: [],
        2: [],
        3: []
      }
    },
    // 取消（一级模态框）
    cancal() {
      this.dialogFormVisible = false
      this.isAddModel = false
      this.editList = {}
      this.arr = []
      this.cardListEdit = {
        4: [],
        1: [],
        2: [],
        3: []
      }
    },

    addCar(type, list) {
      this.form.name = ''
      this.dialogFormVisible = true
      this.cardListEdit = {
        4: [],
        1: [],
        2: [],
        3: []
      }
      this.clearValue()
      // this.getCardEdit()
      /* if (type === 0) { // 添加套餐卡清空数据
        this.editList = {}// 系列列表
      } */
    },

    input(e) {
      if (e === '') {
        this.searchKey = e
        this.pageIndex = 1
        this.carList = []
        this.getCardList()
      }
    },
    // 下拉选项
    onSelect(e) {
      this.selectValue = Number(e)
      this.pageIndex = 1
      this.carList = []
      this.getCardList()
    },
    // 搜索
    onSearch(e) {
      console.log(e)
      this.searchKey = e
      this.pageIndex = 1
      this.carList = []
      this.getCardList()
    }
  }
}
